<template>
  <el-container class="friends_life_cycle">
    <el-main>
      <el-card shadow="never" class="list-title tableCard">
        <vxe-toolbar>
          <template v-slot:buttons>
            <el-button type="primary" icon="el-icon-plus" size="small" @click="openModal('', 1, false)">新增流程</el-button>
          </template>
          <template v-slot:tools>
            <vxe-button class="tool-btn" type="text" size="small" icon="el-icon-refresh" @click="getList()">刷新</vxe-button>
          </template>
        </vxe-toolbar>
        <vxe-table
          ref="xTable"
          border
          resizable
          show-overflow
          highlight-hover-row
          :loading="loading"
          :auto-resize="true"
          :data="activitiesList"
          row-id="id"
          width
          max-height="420"
          :print-config="{}"
          header-align="center"
        >
          <vxe-table-column type="seq" align="center" width="50" title=" " />
          <vxe-table-column field="name" title="流程名称" width="220" />
          <vxe-table-column field="lifeCyclePhaseStr" title="流程阶段" min-width="220" />
          <vxe-table-column field="lifeCycleRightStr" title="可见范围" width="220" />
          <vxe-table-column field="statusDesc" width="80" align="center" title="状态">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.status" :inactive-value="0" :active-value="1" active-text inactive-text @change="changeState(scope)" />
            </template>
          </vxe-table-column>
          <vxe-table-column title="操作" fixed="right" width="150" align="center" slots="default">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="openModal(scope.row.id, 2, true)">查看</el-button>
              <el-button v-if="scope.row.status != 1" type="text" size="mini" @click="openModal(scope.row.id, 2, false)">编辑</el-button>
              <el-button v-if="scope.row.status != 1" type="text" size="mini" @click="del(scope.row.id)">删除</el-button>
            </template>
          </vxe-table-column>
        </vxe-table>
      </el-card>
    </el-main>
    <el-dialog v-if="dialogVisible" width="60%" title="信息编辑" :visible.sync="dialogVisible" :close-on-click-modal="false">
      <el-form ref="ruleForm" :model="params" :rules="rules" label-width="6rem">
        <el-row :gutter="40">
          <el-col :span="24">
            <el-form-item prop="name" label="流程名称：">
              <el-input v-model="params.name" :disabled="diabledEdit" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="remark" label="流程备注：">
              <el-input v-model="params.remark" type="textarea" rows="2" :disabled="diabledEdit" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="lifeCyclePhase" label="阶段设置：">
              <div style="width: 100%;">
                <vxe-toolbar size="mini">
                  <template v-if="!diabledEdit" v-slot:buttons>
                    <vxe-button type="primary" plain icon="el-icon-plus" size="small" @click="openPhaseModal('', '', 1)">新增阶段</vxe-button>
                  </template>
                  <template v-slot:tools>
                    <vxe-button class="tool-btn" type="text" size="small" icon="el-icon-refresh" @click="getPhaseList()">刷新</vxe-button>
                  </template>
                </vxe-toolbar>
                <vxe-table ref="xPhaseTable" border resizable highlight-hover-row :loading="phaseLoading" :auto-resize="true" size="mini" :data="params.lifeCyclePhases" width min-height="220" header-align="center">
                  <vxe-table-column type="seq" align="center" width="50" title=" " />
                  <vxe-table-column field="name" title="阶段名称" width="120" />
                  <vxe-table-column field="remark" title="阶段描述" width="150" show-overflow />
                  <vxe-table-column field="notifyStr" title="阶段提醒" min-width="220">
                    <template slot-scope="scope">
                      <div style="display: inline-block;justify-content: flex-start;">
                        <span v-if="scope.row.needNotify === 1" style="width: 100%;">{{ scope.row.needNotifyStr }}</span>
                        <span v-if="scope.row.needCycleNotify === 1" style="width: 100%;">{{ scope.row.needCycleNotifyStr }}</span>
                      </div>
                    </template>
                  </vxe-table-column>
                  <vxe-table-column v-if="!diabledEdit" title="操作" fixed="right" width="100" align="center" slots="default">
                    <template slot-scope="scope">
                      <el-button v-if="scope.row.status != 1" type="text" size="mini" @click="openPhaseModal(scope.row, scope.$rowIndex, 2)">编辑</el-button>
                      <el-button v-if="scope.row.status != 1" type="text" size="mini" @click="delPhase(scope.$rowIndex)">删除</el-button>
                    </template>
                  </vxe-table-column>
                </vxe-table>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="lifeCycleRight" label="可见范围：">
              <div style="display: inline-flex; position: relative; padding-left: 20px;background: #f8f8f8;width: 100%;vertical-align: middle;">
                <div v-if="!diabledEdit" style="position: relative;text-align: center;vertical-align: middle;margin-top: 10px;">
                  <vxe-button type="info" size="small" icon="el-icon-plus" @click="openRightModal()">添加员工</vxe-button>
                </div>
                <div v-if="params.lifeCycleRights.length >0 && !diabledEdit" style="margin: 10px;background: #fcfcfc;border: 1px solid #d5d5d5;width:90%;">
                  <el-tag v-for="(tag, index) in params.lifeCycleRights" :key="index" type="" hit="true" effect="plain" closable="true" style="margin-left:5px;margin-bottom: 5px;cursor: pointer;" @close="closeTag(index)">{{ tag.name }}</el-tag>
                </div>
                <div v-if="diabledEdit" style="margin: 10px;background: #fcfcfc;border: 1px solid #d5d5d5;width:90%;">
                  <el-tag v-for="(tag, index) in params.lifeCycleRights" :key="index" type="info" hit="true" effect="plain" style="margin-left:5px;margin-bottom: 5px;cursor: pointer;">{{ tag.name }}</el-tag>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="!diabledEdit" type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog v-if="dialogPhaseVisible" width="50%" title="阶段编辑" :visible.sync="dialogPhaseVisible" :close-on-click-modal="false">
      <el-form ref="phaseForm" :model="phaseParams" :rules="phaseRules" label-width="6rem">
        <el-row :gutter="40">
          <el-col :span="22">
            <el-form-item prop="name" label="阶段名称：">
              <el-input v-model="phaseParams.name" />
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item prop="lifeCyclePhase" label="阶段描述：">
              <el-input v-model="phaseParams.remark" type="textarea" rows="3" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="lifeCycleRight" label="跟进提醒：">
              <div style="display: inline-block;justify-content: flex-start;width: 100%;">
                <div>
                  <el-switch v-model="phaseParams.needNotify" :active-value="1" :inactive-value="2" @change="handleNotifyChange" />
                </div>
                <div v-if="phaseParams.needNotify === 1" style="display: inline-block; padding-left: 20px;background: #f8f8f8;width: 100%;vertical-align: middle; margin-top: 10px;">
                  <div style="display: inline-flex;width: 85%; ">
                    <span style="padding: 0 5px 0 5px; ">客户未跟进时间超过:</span>
                    <el-input v-model="phaseParams.daysMissing" size="mini" style="width: 70px;" />
                    <span style="padding: 0 5px 0 5px; ">天后，于:</span>
                    <el-time-picker v-model="phaseParams.timeNotify" placeholder="时间选择" size="mini" value-format="HH:mm:ss" format="HH:mm:ss" :default-value="new Date(0,0,0,9,0,0)" />
                    <span style="padding: 0 5px 0 5px; "> 提醒员工跟进</span>
                  </div>
                  <div style="display: inline-flex;width: 85%; margin-top: 10px; margin-bottom: 10px;">
                    <span style="width: 100px; ">跟进说明：</span>
                    <el-input v-model="phaseParams.followRemark" type="textarea" rows="2" />
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item v-if="phaseParams.needNotify === 1" prop="lifeCycleRight" label="周期提醒：">
              <div style="display: inline-block;justify-content: flex-start;width: 100%;">
                <div>
                  <el-switch v-model="phaseParams.needCycleNotify" :active-value="1" :inactive-value="2" />
                </div>
                <div v-if="phaseParams.needCycleNotify === 1" style="display: inline-block; padding-left: 20px;background: #f8f8f8;width: 100%;vertical-align: middle; margin-top: 10px;">
                  <div style="display: inline-flex;width: 85%; ">
                    <span style="padding: 0 5px 0 5px; ">员工首次提醒未跟进，每:</span>
                    <el-input v-model="phaseParams.daysCycleNotify" size="mini" style="width: 70px;" />
                    <span style="padding: 0 5px 0 5px; ">天，于:</span>
                    <el-time-picker v-model="phaseParams.timeNotifyCycle" placeholder="时间选择" size="mini" value-format="HH:mm:ss" format="HH:mm:ss" :default-value="new Date(0,0,0,9,0,0)" />
                    <span style="padding: 0 5px 0 5px; "> 再次提醒</span>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPhaseVisible = false">取 消</el-button>
        <el-button type="primary" @click="phaseSubmit">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog v-if="dialogRightVisible" width="40%" title="可见范围" :visible.sync="dialogRightVisible" :close-on-click-modal="false">
      <div class="bunk-info-container">
        <div class="left-container">
          <el-card shadow="never" class="bunk-info-list-card">
            <el-tree
              ref="xTree"
              :data="departmentTreeList"
              :props="defaultProps"
              show-checkbox
              :check-on-click-node="true"
              :expand-on-click-node="false"
              default-expand-all
              check-strictly
              node-key="id"
              :current-node-key="currentNodekey"
              @check-change="handleCheckChange"
            />
          </el-card>
        </div>
        <div class="right-container">
          <div style="display: block;width:100%">
            <span>选择的部门、员工</span>
            <div class="vxe-row" style="margin-top: 10px;">
              <vxe-list height="320" class="my-list" :data="params.lifeCycleRights">
                <template #default="{ items }">
                  <div v-for="(item, index) in items" :key="index" class="my-list-item">
                    <span style="font-size: 14px;margin-top: 5px;">{{ item.name }}</span>
                    <span style="float: right;margin-right: 5px;">
                      <i class="el-icon-close" @click="closeSelectedEmployee(item, index)" />
                    </span>
                  </div>
                </template>
              </vxe-list>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRightVisible = false">取 消</el-button>
        <el-button type="primary" @click="rightSubmit">确定</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import { delFriendsLifeCycle, getFriendsLifeCycleList, addFriendsLifeCycle, modifyFriendsLifeCycle, viewFriendsLifeCycle, changeFriendsLifeCycleStatus } from '@/api/cop/lifeCycle'
import { getDepartmentUnionEmployeeTreeList } from '@/api/cop/contact'

export default {
  components: {
  },
  data() {
    return {
      currentNodekey: '1',
      departmentTreeList: [],
      activitiesList: [],
      loading: false,
      phaseLoading: false,
      params: {
        id: '',
        name: '',
        remark: '',
        lifeCyclePhases: [],
        lifeCycleRights: []
      },
      phaseParams: {},
      rightParams: {},
      dialogVisible: false,
      dialogPhaseVisible: false,
      dialogRightVisible: false,
      diabledEdit: true,
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      },
      phaseRules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      },
      operType: 1, // 1 添加 2修改
      phaseSort: 0,
      operPhaseType: 1, // 1 添加 2修改
      props: {
        children: 'children',
        value: 'id',
        label: 'name',
        emitPath: false
      },
      defaultProps: {
        children: 'children',
        label: 'name',
        value: 'id'
      }
    }
  },
  created() {
    this.getList()
    this.getDepartmentList()
  },
  methods: {
    openModal(id, type, bool) {
      this.diabledEdit = bool
      this.operType = type
      this.dialogVisible = true
      if (type === 2) {
        viewFriendsLifeCycle({ id })
          .then(response => {
            if (response) {
              this.params = response
              this.params.lifeCyclePhases = response.lifeCyclePhases
              this.params.lifeCycleRights = response.lifeCycleRights
              this.phaseSort = this.params.lifeCyclePhases.length
            }
          })
      } else {
        this.params.name = ''
        this.params.remark = ''
        this.params.lifeCyclePhases = []
        this.params.lifeCycleRights = []
      }
    },
    openPhaseModal(row, index, type) {
      this.dialogPhaseVisible = true
      this.operPhaseType = type
      this.phaseParams = {}
      if (type === 2) {
        this.phaseParams = row
        this.phaseParams.index = index
      } else {
        index = this.params.lifeCyclePhases.length
        this.phaseSort = this.phaseSort + 1
        this.phaseParams = {
          index: index,
          id: '',
          name: '',
          remark: '',
          sort: this.phaseSort,
          needNotify: 1,
          daysMissing: '20',
          timeNotify: '09:00:00',
          followRemark: '',
          needCycleNotify: 1,
          daysCycleNotify: '5',
          timeNotifyCycle: '21:00:00'
        }
      }
    },
    handleNotifyChange(val) {
      if (val && val === 2) {
        this.phaseParams.needCycleNotify = 2
      }
    },
    closeTag(index) {
      this.$delete(this.params.lifeCycleRights, index)
    },
    delPhase(index) {
      this.$delete(this.params.lifeCyclePhases, index)
    },
    phaseSubmit() {
      this.$refs.phaseForm.validate((valid) => {
        if (valid) {
          if (this.phaseParams.needNotify === 1) {
            // this.phaseParams.timeNotify = this.$moment(this.phaseParams.timeNotify).format('HH:mm:ss')
            this.phaseParams.needNotifyStr = '员工跟进提醒：客户未跟进时间超过' + this.phaseParams.daysMissing + '天后，于' + this.phaseParams.timeNotify + '提醒员工跟进'
          }
          if (this.phaseParams.needCycleNotify === 1) {
            // this.phaseParams.timeNotifyCycle = this.$moment(this.phaseParams.timeNotifyCycle).format('HH:mm:ss')
            this.phaseParams.needCycleNotifyStr = '周期提醒：员工首次提醒未跟进，每' + this.phaseParams.daysCycleNotify + '天，于' + this.phaseParams.timeNotifyCycle + '再次提醒'
          }
          if (this.phaseParams.index && this.phaseParams.index !== '') {
            this.$set(this.params.lifeCyclePhases, this.phaseParams.index, this.phaseParams)
          } else {
            this.$set(this.params.lifeCyclePhases, this.phaseParams.index, this.phaseParams)
          }
          this.dialogPhaseVisible = false
        }
      })
    },
    openRightModal() {
      this.dialogRightVisible = true
      if (this.params && this.params.lifeCycleRights) {
        const selectedTreeNode = []
        this.params.lifeCycleRights.forEach(d => {
          selectedTreeNode.push(d.id)
        })
        if (selectedTreeNode && selectedTreeNode.length > 0) {
          this.$nextTick(() => {
            this.params.lifeCycleRights = []
            this.$refs.xTree.setCheckedKeys(selectedTreeNode)
          })
        }
      }
    },
    closeSelectedEmployee(item, index) {
      this.$delete(this.params.lifeCycleRights, index)
      this.$refs.xTree.setChecked(item.id)
    },
    getList() {
      getFriendsLifeCycleList({}).then(response => {
        if (response) {
          this.activitiesList = response
        }
      })
    },
    getDepartmentList() {
      getDepartmentUnionEmployeeTreeList({ parentId: '0' }).then(res => {
        this.departmentTreeList = res
      })
    },
    handleCheckChange(data, checked, indeterminate) {
      if (checked === true) {
        this.rightParams = {}
        this.rightParams.id = data.id
        this.rightParams.departmentId = data.departmentId
        this.rightParams.employeeId = data.employeeId
        this.rightParams.name = data.name
        this.params.lifeCycleRights.push(this.rightParams)
      } else {
        if (this.params.lifeCycleRights) {
          this.params.lifeCycleRights.forEach((d, index) => {
            if (d.id === data.id) {
              this.$delete(this.params.lifeCycleRights, index)
            }
          })
        }
      }
    },
    rightSubmit() {
      if (this.params.lifeCycleRights && this.params.lifeCycleRights.length <= 0) {
        alert('至少选择一项')
        return false
      } else {
        this.dialogRightVisible = false
      }
    },
    submit() {
      if (this.params === null) {
        alert('参数为空，不能保存！')
        return false
      } else {
        if (this.params.lifeCyclePhases === null || this.params.lifeCyclePhases.length <= 0) {
          alert('流程阶段不能为空，请配置流程阶段！')
          return false
        }
        if (this.params.lifeCycleRights === null || this.params.lifeCycleRights.length <= 0) {
          alert('可见范围不能为空，请配置可见范围！')
          return false
        }
      }
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.operType === 1) {
            addFriendsLifeCycle(this.params).then(response => {
              this.$message.success('添加成功')
              this.dialogVisible = false
              this.getList()
            })
          } else {
            alert(JSON.stringify(this.params))
            modifyFriendsLifeCycle(this.params).then(response => {
              this.$message.success('修改成功')
              this.dialogVisible = false
              this.getList()
            })
          }
        }
      })
    },
    del(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delFriendsLifeCycle({ id }).then(response => {
          this.$message.success('删除成功')
          this.getList()
        })
      })
    },
    changeState(scope) {
      this.activitiesList[scope.seq - 1].status = scope.row.status === 1 ? 0 : 1
      changeFriendsLifeCycleStatus({
        id: scope.row.id,
        status: scope.row.status === 1 ? 0 : 1
      }).then(response => {
        this.activitiesList[scope.seq - 1].status = scope.row.status === 1 ? 0 : 1
        this.$message.success(scope.row.status === 0 ? '禁用成功' : '启用成功')
      })
    }
  }
}
</script>

<style lang="scss">
.friends_life_cycle {
  .bunk-info-container {
    display: flex;
    .left-container {
      margin-right: 20px;
      height:350px;
      border: 1 solid #bababa;
      .bunk-info-list-card {
        height: 100%;
        overflow-y: auto;
        width: 280px;
      }
    }
    .right-container {
      display: inline-block;
      width: calc(100% - 280px);
      .commercia-tenant-list-title {
        margin-bottom: 20px;
        .el-card__body {
          padding:  0;
        }
      }
    }
  }
  .my-list {
    border: 1px solid #d3d5d6;
  }
  .my-list .my-list-item {
    font-size: 14px;
    height: 28px;
    padding: 5px 0 0 15px;
    border: 1px solid #f6f8f9;
  }

}
</style>
